package lucene.server.cdc.util;

import lucene.server.common.dbmeta.ColumnMeta;
import lucene.server.common.dbmeta.DBMetaUtil;
import lucene.server.common.utils.StringUtil;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class FilterUtil {

    public static ConcurrentHashMap<String, List<ColumnMeta>> getFilterMap(Connection conn, List<String> filters) throws SQLException {
        DatabaseMetaData metaData = conn.getMetaData();
        // 获取所有表，格式 数据库::表名
        List<String> allTables = DBMetaUtil.getGetAllTables(metaData);
        ConcurrentHashMap<String, List<ColumnMeta>> filterMap = new ConcurrentHashMap<>();

        for (String table : allTables)
        {
            String[] tableItems = table.split("::");
            String tableCat = tableItems[0];
            String tableName = tableItems[1];
            if ("*.*".equals(filters.get(0))) {
                filterMap.put(tableCat + "::" + tableName, DBMetaUtil.getTableColumns(metaData, tableCat, tableName));
            } else {
                for (String filter : filters) {
                    String[] filterItems = filter.split("\\.");
                    String itemDb = filter.split("\\.")[0];
                    String itemTable = filterItems.length > 1 ? filterItems[1] : "*";
                    if (tableCat.equals(itemDb) && (itemTable.equals("*") || tableName.equals(itemTable))) {
                        filterMap.put(tableCat + "::" + tableName, DBMetaUtil.getTableColumns(metaData, tableCat, tableName));
                    }
                }
            }
        }
        return filterMap;
    }

    public static List<String> getFilter(String filterStr) {
        List<String> filterList = new ArrayList<>();
        if (StringUtil.isNotEmpty(filterStr)) {
            filterList = new ArrayList<>(Arrays.asList(filterStr.split(",")));
            filterList.removeIf(String::isEmpty);
            // 遍历列表并修改
            for (int i = 0; i < filterList.size(); i++) {
                String filter = filterList.get(i);
                if (!filter.contains(".")) {
                    filterList.set(i, filter + ".*");
                } else if (filter.endsWith(".")) {
                    filterList.set(i, filter + "*");
                }
            }
        } else {
            filterList.add("*.*");
        }
        return filterList;
    }
}
